import React, { useState } from 'react'
import { Form, Icon, Input, Button, Modal } from 'antd'
//import { useLocation } from 'react-router-dom'
//import { GITHUB } from '@/config'
//import { save } from '@/utils/storage'
import {PlusCircleOutlined} from '@ant-design/icons';
// redux
import { LOGIN } from '../../../store/action'
import { useDispatch } from 'react-redux'

// hooks
import { useListener } from '../../../hooks/useBus'

const FormItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 }
  }
}

function FormItem(props) {
  const { children, ...rest } = props
  return <Form.Item {...FormItemLayout} {...rest}>{children}</Form.Item>
}

function SignModal(props) {
  const dispatch = useDispatch() // dispatch hooks
  //const location = useLocation() // location
  const [visible, setVisible] = useState(false)
  const [type, setType] = useState('登录')
  const [submitText, setSubmitText] = useState('登录')
  const [submitLoading, setSubmitLoading] = useState(false)
  //表单初始值
  const [initialValues, setInitialValues] = useState('')

  useListener('openSignModal', type => {
    setInitialValues({ account: '', password: '' })
    setType(type)
    setVisible(true)
  })

  function handleSubmit(values) {
    setSubmitLoading(true);
    const action = type === '登录' ? LOGIN : ''
    dispatch(action(values)).then(() => {
        setSubmitLoading(false)
        setVisible(false) // type =  login | register
    }).catch( err => setSubmitLoading(false))
    
  }

  function githubLogin() {
    const { pathname, search } = location
    save('prevRouter', `${pathname}${search}`)
    window.location.href = `${GITHUB.url}?client_id=${GITHUB.client_id}`
  }

  // 确认密码
  function compareToFirstPassword(rule, value, callback) {
    const form = props.form
    if (value && value !== form.getFieldValue('password')) {
      callback('Two passwords that you enter is inconsistent!')
    } else {
      callback()
    }
  }

  return (
    <Modal
      width={460}
      title={type}
      visible={visible}
      className={'signModel'}
      onCancel={e => setVisible(false)}
      footer={null}>
      <Form layout={'horizontal'}  style={{textAlign: 'center'}}
      key={initialValues} initialValues={initialValues} onFinish={handleSubmit}
                      scrollToFirstError>
        {/* {type === 'login' ? ( */}
          <>
            <FormItem label='用户名' name='account' rules = {[{ required: true, message: '用户名不能为空！' }]}>
              {<Input placeholder='请输入用户名' />}
            </FormItem>
            <FormItem label='密码' name='password' rules={[{ required: true, message: '密码不能为空！' }]}>
              {<Input placeholder='请输入密码' type='password' />}
            </FormItem>
          </>
        {/* )
          : (
            <>
              <FormItem label='用户名'>
                {getFieldDecorator('account', {
                  rules: [{ required: true, message: 'Username is required' }]
                })(<Input placeholder='请输入用户名' />)}
              </FormItem>
              <FormItem label='密码'>
                {getFieldDecorator('password', {
                  rules: [{ required: true, message: 'Password is required' }]
                })(<Input placeholder='请输入密码' type='password' />)}
              </FormItem>
              <FormItem label='确认密码'>
                {getFieldDecorator('confirm', {
                  rules: [
                    { required: true, message: 'Password is required' },
                    { validator: compareToFirstPassword }
                  ]
                })(<Input placeholder='确认密码' type='password' />)}
              </FormItem>
              <FormItem label='邮箱'>
                {getFieldDecorator('email', {
                  rules: [
                    { type: 'email', message: 'The input is not valid E-mail!' },
                    { required: true, message: 'Please input your E-mail!' }
                  ]
                })(<Input placeholder='请输入您的邮箱' />)}
              </FormItem>
            </>
          )} */}
        <Button loading={submitLoading} icon={<PlusCircleOutlined/>} type={'primary'}
        htmlType="submit" size={'large'}>{submitText}</Button>
      </Form>
      {/* {GITHUB.enable && (
        <Button block icon='github' onClick={githubLogin} style={{ marginTop: 10 }}>
          github login
        </Button>
      )} */}
    </Modal>
  )
}

export default SignModal